package cn.iocoder.yudao.module.vos.dal.mysql.secretaccount;

import java.math.BigDecimal;
import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.vos.dal.dataobject.secretaccount.SecretAccountDO;
import org.apache.ibatis.annotations.Mapper;
import cn.iocoder.yudao.module.vos.controller.admin.secretaccount.vo.*;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * 密钥管理 Mapper
 *
 * @author shijun
 */
@Mapper
public interface SecretAccountMapper extends BaseMapperX<SecretAccountDO> {

    default PageResult<SecretAccountDO> selectPage(SecretAccountPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<SecretAccountDO>()
                .eqIfPresent(SecretAccountDO::getRechargeTenantId, reqVO.getRechargeTenantId())
                .likeIfPresent(SecretAccountDO::getFilterName, reqVO.getFilterName())
                .eqIfPresent(SecretAccountDO::getAppSecret, reqVO.getAppSecret())
                .betweenIfPresent(SecretAccountDO::getExpireTime, reqVO.getExpireTime())
                .eqIfPresent(SecretAccountDO::getBalance, reqVO.getBalance())
                .eqIfPresent(SecretAccountDO::getEnabled, reqVO.getEnabled())
                .betweenIfPresent(SecretAccountDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(SecretAccountDO::getId));
    }

    @Select("SELECT * FROM vos_secret_account WHERE app_secret = #{appSecret} LIMIT 1")
    SecretAccountDO selectByAppSecret(@Param("appSecret") String appSecret);

    /**
     * CAS 扣费：在余额 >= expectReduce 时，扣减 cost
     * 返回 1 表示成功，0 表示失败（余额不足或并发冲突）
     */
    @Update("UPDATE vos_secret_account " + "SET balance = balance - #{cost}, update_time = NOW() " + "WHERE id = #{id} AND balance >= #{expectReduce}")
    int updateBalanceByCostWithCheck(@Param("id") Long id, @Param("cost") BigDecimal cost, @Param("expectReduce") BigDecimal expectReduce);

}